package com.jxm.spring.security.security.service;

import com.jxm.spring.security.bean.Role;
import com.jxm.spring.security.bean.User;
import com.jxm.spring.security.security.domain.SysUserDetails;
import com.jxm.spring.security.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * @Author: jxm
 * @Description: 用户登录Service
 * @Date: 2021/5/16 19:15
 * @Version: 1.0
 */
@Service
public class SysUserDetailsService implements UserDetailsService{

    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUserName(username);
        if(null != user){
            SysUserDetails sysUserDetails = new SysUserDetails();
            BeanUtils.copyProperties(user,sysUserDetails);
            //角色集合
            HashSet<GrantedAuthority> authorities = new HashSet<>();
            List<Role> roleList  = userService.findRoleByUserId(sysUserDetails.getUserId());
            roleList.forEach(role -> {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
            });
            sysUserDetails.setAuthorities(authorities);
            return sysUserDetails;
        }
        return null;

    }
}
